import { defineStore } from 'pinia'
import { GET_TOKEN, REMOVE_TOKEN, SET_TOKEN } from '@/util/token'
import { constantRouter } from '@/router/routes'
import { reqLogin } from '@/api/user'
import {
  loginFormData,
  loginResponseData,
  userInfoReponseData,
} from '@/api/user/type.ts'
import router from '@/router'

const useUserStore = defineStore('User', {
  state: (): any => {
    return {
      token: GET_TOKEN(),
      menuRoutes: constantRouter,
      username: localStorage.getItem('name'),
      avatar:
        'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
    }
  },
  actions: {
    //用户登录的方法
    async userLogin(data: loginFormData) {
      //登录请求
      const result: userInfoReponseData = await reqLogin(data)
      //登录请求:成功200->token
      //登录请求:失败201->登录失败错误的信息
      console.log(result)
      if (result.code == 200) {
        //pinia仓库存储一下token
        //由于pinia|vuex存储数据其实利用js对象
        this.token = result.data
        this.username = result.data.name

        //本地存储持久化存储一份
        SET_TOKEN(result.data.token)
        localStorage.setItem('name', result.data.name)
        //能保证当前async函数返回一个成功的promise
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },

    userLogout() {
      this.token = ''
      this.username = ''
      REMOVE_TOKEN()
    },
  },
  getters: {},
})

export default useUserStore
